<script setup lang="ts">
import {getSumFile,deleteFileByFileId,createFolder,renameFile} from "@/api/file/fileList.ts";
import {getFileFormat} from "@/utils/file.ts";
import {onMounted, ref} from "vue";
import {createHashFileId} from "@/utils/HashFixedSalt.ts";
import {CircleCloseFilled, Edit, FolderAdd, FolderDelete, Upload} from "@element-plus/icons-vue";
import ContextMenu from "@/components/contentMenu/contentMenu.vue"
import FileDownload from "@/components/file/fileDownload.vue";
import FilePreview from "@/components/file/filePreview.vue";
import router from "@/router";
import {ElMessage, ElMessageBox} from "element-plus";
import FileUpload from "@/components/file/fileUpload.vue";

let fileList = ref([])

const fileDownloadData = ref({
      isShow: false,
      fileName:"",
      fileDate:Object
})

const filePreviewData = ref({
  isShow: false,
  fileList: [],
  folderId: "",
})

let newFile = ref({
  isShow: false,
  fileName:"新建文件夹",
})

let editFile = ref({
  isShow: false,
  fileId:"",
  fileName:"",
  suffix:""
})

const getSumFileList = async () => {
  const response = await getSumFile("0")
  const data = response.data.data
  data.forEach((item:any) => {
    item.suffix = getFileFormat(item.name)
  })
  fileList.value = data
}

onMounted( () => {
  getSumFileList()
})

const showDialog = (item:any) =>{

  // 类型为文件
  if (item.type === 0){
    fileDownloadData.value.isShow = true
    fileDownloadData.value.fileName = item.name
    fileDownloadData.value.fileDate = item
  }
  // 类型为文件夹
  if (item.type === 1){
    filePreviewData.value.isShow = true
    filePreviewData.value.folderId = item.id
  }

}

const handleClose = ()=>{
  fileDownloadData.value.isShow = false
}

const handleCloseFile = ()=>{
  newFile.value.isShow = false
}

const handleCloseFilePreview = ()=>{
  filePreviewData.value.isShow = false
}

const createNewFolder = () => {
  const data = {
    name: newFile.value.fileName,
    fileId: createHashFileId(newFile.value.fileName).hashedFileId,
  }
  createFolder(data).then(res=>{
    if (res.data.code === 200){
      newFile.value.isShow = false
      getSumFileList()
      ElMessage.success('文件夹创建成功');
    }else {
      ElMessage.error(res.data.msg);
    }
  })
}

const handleEditFile = ()=>{
  const name = editFile.value.fileName + '.' + editFile.value.suffix
  const data = {
    fileId: editFile.value.fileId,
    fileName: name,
  }
  renameFile(data).then(res=>{
    if (res.data.code === 200){
      editFile.value.isShow = false
      getSumFileList()
      ElMessage.success('文件重命名成功');
    }
  })
}

const selectFile = (label:any,item:any) => {
  if (label === "上传文件"){
    router.push('/upload')
  }
  if (label === "删除文件"){
    ElMessageBox.confirm(
        `确定删除——${item.name}？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
      .then(() => {
        deleteFileByFileId(item.fileId).then((res:any) => {
          if (res.data.code === 200){
            return getSumFileList()
          }
        }).then(() => {
          ElMessage.success('文件删除成功');
        })
            .catch((error: any) => {
              console.error('删除文件失败：', error);
            });
      })

  }
  if (label === "新建文件夹"){
    newFile.value.isShow = true
  }
  if (label === "重命名"){
    editFile.value.isShow = true
    editFile.value.fileId = item.fileId
    const fileName = item.name
    const lastIndex = fileName.lastIndexOf(".")
    editFile.value.suffix = fileName.substring(lastIndex+1)
    editFile.value.fileName = fileName.substring(0,lastIndex)
  }
}

</script>

<template>

  <ContextMenu :menu="[
      {label:'新建文件夹',icon:FolderAdd},
      {label:'上传文件',icon:Upload},
      ]" @select="selectFile($event.label,null)" >
    <div class="bg">
      <el-empty v-show="fileList.length === 0" description="用户暂未上传文件" />
      <div class="file-content">
        <div class="list-box" v-for="item in fileList" @click="showDialog(item)">
          <ContextMenu v-if="fileList.length !== 0" :menu="[
              {label:'删除文件',icon:FolderDelete},
              {label:'重命名',icon:Edit},
              ]" @select="selectFile($event.label,item)" >
          <el-icon :class="item.suffix" :size="80"/>
          <div>
            <p class="box-name">{{item.name}}</p>
            <p class="box-time">{{item.createdAt}}</p>
          </div>
          </ContextMenu>
        </div>
      </div>
      <div class="add-btn">
        <file-upload pid="0" @upload-success="getSumFileList">
          <el-button type="primary">
            <el-icon class="el-icon--right"><Upload /></el-icon>
            文件上传
          </el-button>
        </file-upload>
      </div>
  </div>
</ContextMenu>
  <FileDownload @close="handleClose" :file-date="fileDownloadData?.fileDate" :file-title="fileDownloadData?.fileName" :download-dialog-visible="fileDownloadData?.isShow"/>
  <FilePreview @close="handleCloseFilePreview" :folder-id="filePreviewData?.folderId" :file-list="filePreviewData?.fileList" :download-dialog-visible="filePreviewData?.isShow"/>
  <el-dialog
      v-model="newFile.isShow"
      width="30%"
      :show-close="false"
      :before-close="handleCloseFile"
  >
    <template #header="{ close, titleId }">
      <div class="my-header">
        <span :id="titleId" >新建文件夹</span>
        <el-button type="danger" @click="close">
          <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
          关闭
        </el-button>
      </div>
    </template>
    <el-input v-model="newFile.fileName" placeholder="请输入文件夹名称" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="newFile.isShow = false">取 消</el-button>
        <el-button type="primary" @click="createNewFolder">确 定</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog
      v-model="editFile.isShow"
      width="30%"
      :show-close="false"
  >
    <template #header="{ close, titleId }">
      <div class="my-header">
        <span :id="titleId" >重命名</span>
        <el-button type="danger" @click="close">
          <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
          关闭
        </el-button>
      </div>
    </template>
    <el-input v-model="editFile.fileName" placeholder="请输入文件名称" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editFile.isShow = false">取 消</el-button>
        <el-button type="primary" @click="handleEditFile">确 定</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<style scoped lang="scss">
::v-deep(.el-upload-dragger){
  border: unset;
}

.bg{
  height: calc(100vh - 20px);
  width: 100%;

  .add-btn{
    position: absolute;
    bottom: 20px;
    right: 30px;
    z-index: 999;
  }

  .my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    gap: 16px;
  }

  .file-content{
    margin:auto;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(185px, 1fr));
    gap: 10px;
    overflow-y:auto ;

    .list-box{
      width: 155px;
      min-height: 180px;
      margin: 10px;
      border-radius: 10px;
      cursor: pointer;

      .box-name{
        font-size: 14px;
        font-weight: 600;
        margin: unset;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .box-time{
        font-size: 12px;
        color: #CDD0D6;
      }
    }

    .list-box:hover{
      background-color: #D9ECFF;
    }
  }
}
</style>
